package com.terry.sp.web;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.terry.sp.core.Result;
import com.terry.sp.core.ResultGenerator;
import com.terry.sp.model.Device;
import com.terry.sp.service.DeviceService;
import com.terry.sp.websocket.DeviceServer;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created by CodeGenerator on 2019/04/21.
 */
@RestController
@RequestMapping("/device")
public class DeviceController{
    @Resource
    private DeviceService deviceService;

    @RequestMapping("/checkStatus")
    public Result checkStatus(@RequestParam int deviceId) {
        int result = DeviceServer.checkDeviceStatus(deviceId);
        return ResultGenerator.genSuccessResult(result);
    }

    @PostMapping("/add")
    public Result add(@RequestBody Device device) {
        deviceService.save(device);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/delete")
    public Result delete(@RequestParam Integer id) {
        deviceService.deleteById(id);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/update")
    public Result update(Device device) {
        deviceService.update(device);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/detail")
    public Result detail(@RequestParam Integer id) {
        Device device = deviceService.findById(id);
        device.setState(DeviceServer.checkDeviceStatus(id));
        return ResultGenerator.genSuccessResult(device);
    }

    @PostMapping("/list")
    public Result list(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<Device> list = deviceService.findAll();
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }
}
